package cn.exrick.xboot.modules.portal.controller;


import cn.exrick.xboot.common.constant.CommonConstant;
import cn.exrick.xboot.common.utils.ResultUtil;
import cn.exrick.xboot.common.utils.SecurityUtil;
import cn.exrick.xboot.common.utils.jiuqi.utils.ServeUtil;
import cn.exrick.xboot.common.vo.Result;
import cn.exrick.xboot.modules.backlogOrFullList.entity.BacklogOrFullList;
import cn.exrick.xboot.modules.backlogOrFullList.service.IbacklogOrFullListService;
import cn.exrick.xboot.modules.base.entity.Department;
import cn.exrick.xboot.modules.base.entity.User;
import cn.exrick.xboot.modules.base.service.DepartmentService;
import cn.exrick.xboot.modules.commonLink.entity.CommonLink;
import cn.exrick.xboot.modules.commonLink.service.ICommonLinkService;
import cn.exrick.xboot.modules.downloadResources.entity.DownloadResources;
import cn.exrick.xboot.modules.downloadResources.service.IDownloadResourcesService;
import cn.exrick.xboot.modules.information.entity.Information;
import cn.exrick.xboot.modules.information.service.IInformationService;
import cn.exrick.xboot.modules.news.entity.NewsImages;
import cn.exrick.xboot.modules.news.entity.news;
import cn.exrick.xboot.modules.news.service.INewsImagesService;
import cn.exrick.xboot.modules.news.service.InewsService;
import cn.exrick.xboot.modules.portalConfig.entity.PortalConfig;
import cn.exrick.xboot.modules.portalConfig.service.IPortalConfigService;
import cn.exrick.xboot.modules.subsystemNews.entity.SubsystemNews;
import cn.exrick.xboot.modules.subsystemNews.service.ISubsystemNewsService;
import cn.exrick.xboot.modules.system.entity.System;
import cn.exrick.xboot.modules.system.service.ISystemService;
import cn.exrick.xboot.modules.system.serviceimpl.ISystemServiceImpl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@Api(description = "portal首页特定数据")
@RequestMapping("/xboot/portalController")
@Transactional
public class portalController {
    @Autowired
    private ISubsystemNewsService iSubsystemNewsService;

    @Autowired
    private IInformationService iInformationService;

    @Autowired
    private ISystemService iSystemService;

    @Autowired
    private InewsService inewsService;

    @Autowired
    private INewsImagesService iNewsImagesService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private  IPortalConfigService iPortalConfigService;

    @Autowired
    private IDownloadResourcesService iDownloadResourcesService;

    @Autowired
    private ICommonLinkService iCommonLinkService;
    @Autowired
    private IbacklogOrFullListService ibacklogOrFullListService;

    @Autowired
    private SecurityUtil securityUtil;

    @Value("${server.port}")
    private String port;
    @Value("${portal.portalType}")
    private String portalType;
    @RequestMapping(value = "/selectNoticePortal", method = RequestMethod.GET)
    @ApiOperation(value = "子系统公告portal数据获取")
    public Result<List<Object>> selectNoticePortal(@Param("num") Integer num, @Param("departmentId") String departmentId) {
        log.info("调用selectNoticePortal（）子系统公告portal数据获取:" + "num:" + num + "departmentId:" + departmentId);
        Map<String, Object> map = new HashMap<String, Object>();
        /*if (departmentId != null && !departmentId.equals("") && departmentId.length() != 0 && !departmentId.trim().isEmpty()) {
            //通过部门id查询部门名字
            Department department = departmentService.get(departmentId);
            map.put("department", department.getTitle());
        }*/
        if (num != null && !num.equals("")) {
            map.put("num", num);
        }
        List<Object> subsystemNotice = iSubsystemNewsService.selectNoticePortal(map);
        int size = subsystemNotice.size();
        return new ResultUtil<List<Object>>().setData(subsystemNotice, size);
    }

    @RequestMapping(value = "/selectInformationPortal", method = RequestMethod.GET)
    @ApiOperation(value = "portal获取子系统新消息通知")
    public Result<List<Information>> selectInformationPortal(@Param("num") Integer num, @Param("departmentId") String departmentId) {
        log.info("调用selectInformationPortal（） ，portal获取子系统新消息通知:" + "num:" + num + "departmentId:" + departmentId);
        Map<String, Object> map = new HashMap<String, Object>();
      /*  if (departmentId != null && !departmentId.equals("") && departmentId.length() != 0 && !departmentId.trim().isEmpty()) {
            //通过部门id查询部门名字
            Department department = departmentService.get(departmentId);
            map.put("department", department.getTitle());
        }*/
        if (num != null && !num.equals("")) {
            map.put("num", num);
        }
        List<Information> information = iInformationService.selectInformationPortal(map);
        int size = information.size();
        return new ResultUtil<List<Information>>().setData(information, size);
    }

    /**
     *modifier njp 将返回数据重新包装成一个对象 20190830 begin
     * （对前端接口风格做调整）
     */
/*    @RequestMapping(value = "/selectNewsPortal", method = RequestMethod.GET)
    @ApiOperation(value = "portal新闻信息")
    public Result<Object> selectNewsPortal(@Param("num") Integer num, @Param("departmentId") String departmentId) {
        //1.获取指定数量与指定组织部门的子系统的新闻
        log.info("调用selectNewsPortal（）查询" + num + "条子系统新闻数据");
        Map<String, Object> map = new HashMap<String, Object>();
        if (num != null && !num.equals("")) {
            map.put("num", num);
        }
        if (departmentId != null && !departmentId.equals("") && departmentId.length() != 0 && !departmentId.trim().isEmpty()) {
            //通过部门id查询部门名字
            Department department = departmentService.get(departmentId);
            map.put("department", department.getTitle());
        }
        List<SubsystemNews> subsystemNewslist = iSubsystemNewsService.selectNewsByNum(map);
      *//* // 2.获取本地置顶新闻（置顶：news_is_top字段为0时）
       List<news> news = inewsService.selectNewsByTop("0");*//*
        //2.获取本地新闻
        List<news> news = inewsService.list();
        //3.获取新闻主图地址
        //String getImage=null;
        if(news.size()>0) {
            for (int i = 0; i < news.size(); i++) {
                NewsImages newsImages1 = iNewsImagesService.selectNewsImagesByNewsId(news.get(i).getId());
                String name=null;
                if(newsImages1!=null){
                    name = newsImages1.getName();
                }else {
                    name="default.jpg";
                }

                //获取访问前缀
                PortalConfig config = iPortalConfigService.selectPortalConfigByKey("url");
                String url = config.getValue();
                //拼接访问地址：  前缀+图片地址+图片名字
                String  getImage = url + CommonConstant.IMAGE_PATH + name;
                //20190830 在此处将将本地新闻存储到新对象集合(subsystemNewslist)中
                SubsystemNews  subsystemNews=new SubsystemNews();
                subsystemNews.setId(news.get(i).getId());
                subsystemNews.setCreateTime(news.get(i).getCreateTime());
                subsystemNews.setUpdateTime(news.get(i).getUpdateTime());
                subsystemNews.setTitle(news.get(i).getNewsTitle());
                subsystemNews.setImageUrl(getImage);
                //（本地：1，异构：0）
                subsystemNews.setInfoCode("1");
                subsystemNewslist.add(subsystemNews);

            }

        }
        //对数据进行排序
        List<SubsystemNews> subsystemNews = portalController.bubbleSortForTime(subsystemNewslist);
        return new ResultUtil<Object>().setDoubleData(subsystemNews);
    }*/
    /**
     *modifier njp 将返回数据重新包装成一个对象 20190830 end
     * （对前端接口风格做调整）
     */


    @RequestMapping(value = "/selectNewsPortal", method = RequestMethod.GET)
    @ApiOperation(value = "portal新闻信息")
    public Result<Object> selectNewsPortal(@ModelAttribute news infoNews) {
       /* InetAddress address = null;//获取的是本地的IP地址
        try {
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        String IP = address.getHostAddress();//192.168.0.121*/
        String IP =ServeUtil.getInet4Address();
        //默认图片名
        String defaultImageName="default.png";
        log.info("调用selectNewsPortal接口获取新闻信息begin");
        //List<news> newsList = inewsService.selectPortalNewsVoMap(infoNews);
        //List<news> newsList = inewsService.selectPortalNewsvoDict(infoNews);
        List<news> newsList = inewsService.selectPortalNewsvoDict(infoNews);

        for (int i = 0; i < newsList.size(); i++) {
            if("1".equals(newsList.get(i).getInfoCode())){//0.异构系统数据 1:本地数据
                NewsImages newsImages1 = iNewsImagesService.selectNewsImagesByNewsId(newsList.get(i).getId());
                String name=null;
                if(newsImages1!=null){
                    name = newsImages1.getName();
                }else {
                    name=defaultImageName;
                }
                //拼接访问地址：  前缀+图片地址+图片名字
                String  getImage = "http://"+IP+":"+port+CommonConstant.IMAGE_PATH+name;
                newsList.get(i).setImageUrl(getImage);
            }else {
                if(newsList.get(i).getImageUrl()==null){
                    //String getImage=  "http://"+IP+":"+port+CommonConstant.IMAGE_PATH+newsList.get(i).ge;
                    /**
                     *  njp 20200224获取资源服务器的port的改造 begin
                     */
                    String  fileProjectPort =ServeUtil.getFilrProject();
                    /**
                     *  njp 20200224 获取资源服务器的port的改造 end
                     */
                    String getImage=  "http://"+IP+":"+fileProjectPort+CommonConstant.IMAGE_PATH+defaultImageName;
                    //String  getImage = url + CommonConstant.IMAGE_PATH + defaultImageName;
                    newsList.get(i).setImageUrl(getImage);
                }
              continue;
            }
        }
        log.info("调用selectNewsPortal接口获取新闻信息end");
        return new ResultUtil<Object>().setDoubleData(newsList);
    }



    @RequestMapping(value = "/selectSystemPortal", method = RequestMethod.GET)
    @ApiOperation(value = "portal获取快捷入口信息")
    public Result<Object> selectSystemPortal(@ModelAttribute User user) {
        log.info("获取登录用户的身份证信息" + user.getIdcard());

        List<System> systems = iSystemService.selectSystemPortal(user);
        /**
         * 20200603  njp add 改造单点地址 需求：内外网权限配置 begin
         * add 根据登录用户判断该用户使用的单点地址
         */
        //获取当前登录用户
        User u = securityUtil.getCurrUser();
        List<System> checkSystems = iSystemService.checkSysByAcu(systems, u);

        /**
         * 20200603  njp add 改造单点地址 需求：内外网权限配置 end
         */
        return new ResultUtil<Object>().setData(checkSystems);
    }



    @RequestMapping(value = "/selectCommonLinkByNum", method = RequestMethod.GET)
    @ApiOperation(value = "portal获取常用链接")
    public Result<Object> selectCommonLinkByNum(@Param("num") Integer num) {
        log.info("查询" + num + "条常用链接");
        Map<String, Object> map = new HashMap<String, Object>();
        if (num != null && !num.equals("")) {
            map.put("num", num);
        }
        List<CommonLink> commonLinks = iCommonLinkService.selectCommonLinkByNum(map);
        return new ResultUtil<Object>().setData(commonLinks);
    }

    @RequestMapping(value = "/selectDownloadResourcesByNumAndDep", method = RequestMethod.GET)
    @ApiOperation(value = "portal获取常用下载")
    public Result<List<DownloadResources>> selectDownloadResourcesByNumAndDep(@Param("num") Integer num, @Param("departmentId") String departmentId) {
        log.info("selectDownloadResourcesByNumAndDepportal获取常用下载：num:" + num + "departmentId:" + departmentId);
        Map<String, Object> map = new HashMap<String, Object>();
       /* if (departmentId != null && !departmentId.equals("") && departmentId.length() != 0 && !departmentId.trim().isEmpty()) {
            //通过部门id查询部门名字
            Department department = departmentService.get(departmentId);
            map.put("department", department.getTitle());
        }*/
        if (num != null && !num.equals("")) {
            map.put("num", num);
        }
        List<DownloadResources> downloadResources = iDownloadResourcesService.selectDownloadResourcesByNumAndDep(map);
        int size = downloadResources.size();
        return new ResultUtil<List<DownloadResources>>().setData(downloadResources, size);
    }

    @RequestMapping(value = "/selectBacklogOrFullListByMap", method = RequestMethod.GET)
    @ApiOperation(value = "portal待办已办")
    public Result<List<BacklogOrFullList>> selectBacklogOrFullListByMap(@ModelAttribute BacklogOrFullList backlogOrFullList,@Param("num") Integer num) {
        //log.info("selectBacklogOrFullListByMap查询条件："+num+","+backlogOrFullList.toString());
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("backlogOrFullList",backlogOrFullList);
        map.put("num",num);
        List<BacklogOrFullList> backlogOrFullLists = ibacklogOrFullListService.selectBacklogOrFullListByMap(map);

        return new ResultUtil<List<BacklogOrFullList>>().setData(backlogOrFullLists);
        }




    @RequestMapping(value = "/selectTest", method = RequestMethod.GET)
    @ApiOperation(value = "")
    public Result<Object> selectNewsPortal(HttpServletRequest request) {
        //String path = request.getSession().getServletContext().getRealPath("/upload/");
        //String realPath = request.getSession().getServletContext().getRealPath("");

        PortalConfig url = iPortalConfigService.selectPortalConfigByKey("url");

        //log.info("当前服务访问地址"+realPath);
        return null;
    }

    /**
     * add njp 20190830按时间给集合排序 begin
     * @param list
     * @return
     */
    public static List<SubsystemNews> bubbleSortForTime(List<SubsystemNews> list){
        int count=0;
        for (int j = 0; j < list.size(); j++) {
            int flag=0;
            for(int i=1;i<list.size();i++){
                count=count+1;
                //按时间倒序排序
                if(list.get(i-1).getCreateTime().before(list.get(i).getCreateTime())){
                //按时间正序排序
                //if(list.get(i-1).getCreateTime().after(list.get(i).getCreateTime())){
                    flag=1;
                    SubsystemNews sub=null;
                    sub=list.get(i-1);
                    list.set((i-1),list.get(i));
                    list.set(i, sub);
                }
            }
            if(flag==0){
                break;
            }
        }
        log.info("cycles:"+count);
        return list;
    }
    /**
     * add njp 20190830按时间给集合排序 end
     */

    /**
     * njp add 20200401
     * 添加关于portalType的配置用于区分不同的portal系统
     */
    @RequestMapping(value = "/getPortalType", method = RequestMethod.GET)
    @ApiOperation(value = "获取portalType的配置用于区分不同的portal系统（调用该接口建议设置成全局变量调用一次即可）")
    public Result<Object> getPortalType( ) {
        Map map=new HashMap();
        map.put("portalType",portalType);
        return new ResultUtil<Object>().setData(map);
        //return portalType;
    }
}
